import Cookies from 'react-cookies'
import { getDomain } from './index';
const { NODE_ENV } = process.env;
const expires = new Date(Date.now() + 1000 * 60 * 60 * 24 * 15) // 15天
const hostName = getDomain()

export const prefix = NODE_ENV == 'development' ? 'dev_' : 'pro_';

console.log(`NODE_ENV----${NODE_ENV}`)

/**
 *  获取本地guid 或者token
 * @param str  String  guid || token
 * @returns {string} String guid
 */
export function getFlag(str: string) {

	return Cookies.load(prefix + str)
	// return localStorage.getItem(prefix + str);
}

/**
 * 设置本地缓存guid || token
 * @param key
 * @param value
 */
export function setFlag(key: string, value: any, session = false) {

	if (value) {
		const opt: { expires?: any, domain: string, path: string } = { domain: hostName, path: '/' }
		if (!session) {
			opt.expires = expires
		}
		return Cookies.save(prefix + key, value, { ...opt })
		// return localStorage.setItem(prefix + key, value);
	}
}

/**
 * 移除缓存
 * @param key 缓存对应键
 */
export function removeItem(key: string) {
	return Cookies.remove(prefix + key, { domain: hostName })
	// return localStorage.removeItem(prefix + key);
}

/**
 * 设置用户guid
 * @returns 
 */
export function setUserId(user_id: string) {
	return setFlag('user_guid', user_id)
}

/**
 * 设置用户token
 * @returns 
 */
export function setUserToken(token: string) {
	return setFlag('user_token', token)
}

/**
 * 获取用户guid
 * @returns 
 */
export function getUserId() {
	return getFlag('user_guid')
}

/**
 * 获取用户token
 * @returns 
 */
export function getUserToken() {
	return getFlag('user_token')
}

/**
 * 清除用户登录信息
 * @returns 
 */
export function removeUser() {
	removeItem('user_guid')
	removeItem('user_token')
	return true
}